<?php

namespace App\Jobs;

use App\Events\ApkUploaded;
use App\Models\Game\Center\Apk;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;

class UploadApk implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $apk;

    /**
     * UploadApk constructor.
     * @param Apk $apk
     */
    public function __construct(Apk $apk)
    {
        $this->apk = $apk;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //if ($this->apk->status === Apk::STATUS_MAKED) return true;
        if (!app()->isLocal()) {
            $filePath = Storage::disk('static')->path($this->apk->path);
            Storage::disk('oss')->putFileAs('/', $filePath, $this->apk->path);

            // 上传成功后删除本地APK
            Storage::disk('static')->delete($this->apk->path);
        }

        $this->apk->status = Apk::STATUS_UPLOAD;
        $this->apk->save();

        event(new ApkUploaded($this->apk));
        info(__METHOD__, ['操作成功', $this->apk->download_url]);
    }
}
